package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author liuyp
 * @date 2021/01/29
 */
@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findMaxScoreUser(long userId) {
        //db.recommend_user.find({toUserId: 112}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score")))
                .limit(1);

        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageResult<RecommendUser> findRecommendUserList(long userId, int page, int pagesize) {
        //1. 准备查询条件
        Criteria criteria = Criteria.where("toUserId").is(userId);
        //2. 设置排序和分页信息
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))
                .with(PageRequest.of(page-1, pagesize));

        //3. 从MongoDB里查询数据列表
        List<RecommendUser> userList = mongoTemplate.find(query, RecommendUser.class);
        //4. 从MongoDB里查询总数量
        long count = mongoTemplate.count(query, RecommendUser.class);
        //5. 封装并返回结果PageResult
        int pages = (int) Math.ceil((count * 1.0 / pagesize));
        return new PageResult<>((int)count, pagesize, pages, page, userList);
    }

    @Override
    public Integer findRecommendScore(long targetUserId, long userId) {
        Criteria criteria = Criteria.where("userId").is(targetUserId).and("toUserId").is(userId);
        RecommendUser recommendUser = mongoTemplate.findOne(new Query(criteria), RecommendUser.class);
        if (recommendUser == null) {
            return 95;
        }
        return recommendUser.getScore().intValue();
    }
}
